package com.letao.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letao.server.dto.BatchOrderDTO;
import com.letao.server.dto.PageDTO;
import com.letao.server.dto.Result;
import com.letao.server.entity.*;
import com.letao.server.mapper.*;
import com.letao.server.service.*;
import com.letao.server.utils.RegexUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderService {
    private static String[] orderStatusList = {"已取消", "已创建", "已支付", "已取货", "已发货", "已收货", "已退货"};
    private static String[] paymentMethodList = {"微信", "支付宝", "银行卡"};
    private static String[] deliveryMethodList = {"快递", "线下取货"};
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBaseRegionService baseRegionService;
    @Resource
    private SkuCommentInfoMapper skuCommentInfoMapper;
    @Resource
    private IOrderDetailSeckillService orderDetailSeckillService;
    @Resource
    private SeckillInfoMapper seckillInfoMapper;
    @Resource
    private IOrderDetailService orderDetailService;
    @Resource
    private SpuInfoMapper spuInfoMapper;
    @Resource
    private IShopService shopService;

    /**
     * 用于有条件的分页批量查询订单信息
     * 接口等级：管理员
     *
     * @param userId           用户id
     * @param addresseeName    收件人姓名
     * @param addresseeSex     收件人性别
     * @param provinceId       省级编号
     * @param cityId           市级编号
     * @param districtId       区级编号
     * @param paymentMethod    支付方式
     * @param orderMoneyBottom 范围匹配的最小金额
     * @param orderMoneyTop    范围匹配的最大金额
     * @param orderStatus      订单状态
     * @param deliveryMethod   配送方式
     * @param shopId           取货店铺id
     * @param begin            订单创建开始时间
     * @param end              订单创建结束时间
     * @param page             查询页码
     * @param pageSize         查询页的大小
     * @return Result 返回的数据
     */
    @Override
    public Result getPageInfo(Long orderId, String userName, Long userId, String addresseeName, Integer addresseeSex, Integer provinceId, Integer cityId, Integer districtId, Integer paymentMethod, Double orderMoneyBottom, Double orderMoneyTop, Integer orderStatus, Integer deliveryMethod, Integer shopId, String begin, String end, Integer isSeckill, Integer commentState, Integer page, Integer pageSize) {
        IPage<OrderInfo> orderPage = new Page<>(page, pageSize);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        List<Long> userIdList;
        //如果用用户名
        if (userName != null) {
            userInfoQueryWrapper.like("account", userName).select("id");
            List<UserInfo> users = userInfoMapper.selectList(userInfoQueryWrapper);
            userIdList = users.stream().map(UserInfo::getId).collect(Collectors.toList());
            if (!userIdList.isEmpty())
                wrapper.in("user_id", userIdList);
            else {
                wrapper.eq("id", -1);
            }
        }
        //如果用用户id
        if (userId != null) wrapper.likeRight("user_id", userId);
        //用收件人姓名
        if (addresseeName != null) wrapper.like("addressee_name", addresseeName);
        //用收件人性别
        if (addresseeSex != null) if (addresseeSex == 0 || addresseeSex == 1) wrapper.eq("addressee_sex", addresseeSex);
        //用地区
        if (provinceId != null) wrapper.eq("province", provinceId);
        if (cityId != null) wrapper.eq("city", cityId);
        if (districtId != null) wrapper.eq("district", districtId);
        //用支付方式
        if (paymentMethod != null) wrapper.eq("payment_method", paymentMethod);
        //用金额来匹配
        if (orderMoneyBottom != null && orderMoneyTop != null)
            wrapper.between("order_money", orderMoneyBottom, orderMoneyTop);
        //用订单状态
        if (orderStatus != null) wrapper.eq("order_status", orderStatus);
        //用配送方式
        if (deliveryMethod != null) wrapper.eq("delivery_method", deliveryMethod);
        //用取货店铺id
        if (shopId != null) wrapper.eq("shop_id", shopId);
        //指定订单时间段
        if (begin != null && end != null) {
            if (RegexUtils.isDateFromInvalid(begin) && RegexUtils.isDateFromInvalid(end)) {
                wrapper.between("create_time", begin, end);
            }
        }
        if (isSeckill != null) wrapper.eq("is_seckill", isSeckill);
        if (orderId != null) wrapper.likeRight("id", orderId);
        if (commentState != null) wrapper.eq("comment_state", commentState);


        //查询
        IPage<OrderInfo> orderInfoIPage = orderInfoMapper.selectPage(orderPage, wrapper);
        List<BatchOrderDTO> batchOrderDTOList = new ArrayList<>();

        for (OrderInfo record : orderInfoIPage.getRecords()) {

            BatchOrderDTO batchOrderDTO = BeanUtil.copyProperties(record, BatchOrderDTO.class);
            if(batchOrderDTO.getDeliveryMethod()==1){
                batchOrderDTO.setProvinceName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getProvinceId()).getName());
                batchOrderDTO.setCityName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getCityId()).getName());
                batchOrderDTO.setDistrictName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getDistrictId()).getName());
            }else {
                batchOrderDTO.setProvinceName(baseRegionService.getById(record.getProvince()).getName());
                batchOrderDTO.setCityName(baseRegionService.getById(record.getCity()).getName());
                batchOrderDTO.setDistrictName(baseRegionService.getById(record.getDistrict()).getName());
            }
            batchOrderDTO.setUserName(userService.getById(record.getUserId()).getAccount());
            BaseRegion province = baseRegionService.getById(record.getProvince());
            if (province != null) batchOrderDTO.setProvinceName(province.getName());
            BaseRegion city = baseRegionService.getById(record.getCity());
            if (city != null) batchOrderDTO.setCityName(city.getName());
            BaseRegion district = baseRegionService.getById(record.getDistrict());
            if (district != null) batchOrderDTO.setDistrictName(district.getName());
            if (record.getIsSeckill() == 1) {
                OrderDetailSeckill one = orderDetailSeckillService.query().eq("order_id", record.getId()).one();
                SeckillInfo seckillInfo = seckillInfoMapper.selectById(one.getSeckillId());
                batchOrderDTO.setOrderImage(seckillInfo.getSeckillImage());
            } else {
                List<OrderDetail> list = orderDetailService.query().eq("order_id", record.getId()).list();
                if (!list.isEmpty()) {
                    OrderDetail orderDetail = list.get(0);
                    SpuInfo spu = spuInfoMapper.selectById(orderDetail.getSpuId());
                    batchOrderDTO.setOrderImage(spu.getSpuImage());
                }

            }
            ShopInfo shop = shopService.getById(record.getShopId());
            if (shop != null) batchOrderDTO.setShopName(shop.getName());
            batchOrderDTO.setStringOrderStatus(orderStatusList[batchOrderDTO.getOrderStatus()]);
            batchOrderDTO.setStringPaymentMethod(paymentMethodList[batchOrderDTO.getPaymentMethod()]);
            batchOrderDTO.setStringDeliveryMethod(deliveryMethodList[batchOrderDTO.getDeliveryMethod()]);
            StringBuilder str = new StringBuilder();
            str.append(batchOrderDTO.getProvinceName() + ",");
            str.append(batchOrderDTO.getCityName() + ",");
            str.append(batchOrderDTO.getDistrictName() + ",");
            str.append(batchOrderDTO.getDetail());
            batchOrderDTO.setAddress(str.toString());
            batchOrderDTOList.add(batchOrderDTO);

        }
        Collections.reverse(batchOrderDTOList);
        //构造返回结果
        PageDTO<BatchOrderDTO> batchOrderPageDTO = new PageDTO<>();
        batchOrderPageDTO.setRows(batchOrderDTOList);
        batchOrderPageDTO.setTotalSize(orderInfoIPage.getTotal());
        batchOrderPageDTO.setPages(orderInfoIPage.getPages());
        batchOrderPageDTO.setPageSize(orderInfoIPage.getSize());
        batchOrderPageDTO.setCurrentPage(orderInfoIPage.getCurrent());
        log.info("管理员批量查询了订单信息");
        return Result.success(batchOrderPageDTO);
    }


    @Override
    public Result getInfo(Long id) {
        BatchOrderDTO batchOrderDTO = BeanUtil.copyProperties(getById(id), BatchOrderDTO.class);
        if(batchOrderDTO.getDeliveryMethod()==1){
            batchOrderDTO.setProvinceName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getProvinceId()).getName());
            batchOrderDTO.setCityName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getCityId()).getName());
            batchOrderDTO.setDistrictName(baseRegionService.getById(shopService.getById(batchOrderDTO.getShopId()).getDistrictId()).getName());
        }else {
            batchOrderDTO.setProvinceName(baseRegionService.getById(getById(id).getProvince()).getName());
            batchOrderDTO.setCityName(baseRegionService.getById(getById(id).getCity()).getName());
            batchOrderDTO.setDistrictName(baseRegionService.getById(getById(id).getDistrict()).getName());
        }
        batchOrderDTO.setUserName(userService.getById(getById(id).getUserId()).getAccount());


        QueryWrapper<SkuCommentInfo> skuCommentWrapper = new QueryWrapper<>();
        skuCommentWrapper.eq("order_id", id);
        List<SkuCommentInfo> skuCommentInfos = skuCommentInfoMapper.selectList(skuCommentWrapper);
        if (!skuCommentInfos.isEmpty()) {
            SkuCommentInfo skuCommentInfo = skuCommentInfoMapper.selectOne(skuCommentWrapper);
            batchOrderDTO.setCommentState(skuCommentInfo.getCommentState());
        } else {
            batchOrderDTO.setCommentState(0);
        }
        return Result.success(batchOrderDTO);
    }
}
